package es.cea.servlets;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HolaImagenServlet
 */
public class HolaImagenServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String pathImagen;
		if(request.getParameter("user")!=null && request.getParameter("user").equals("admin")){
			pathImagen = "/WEB-INF/img/giralda.jpg";
			
		}else{
			pathImagen = "/WEB-INF/img/privado.jpg";
		}
	   ServletContext sc = request.getSession().getServletContext();
		String filename = sc.getRealPath(pathImagen);

           // Get the MIME type of the image
           String mimeType = sc.getMimeType(filename);
           if (mimeType == null) {
               sc.log("Could not get MIME type of "+filename);
               response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
               return;
           }

           // Set content type
           response.setContentType(mimeType);

           // Set content size
           File file = new File(filename);
           response.setContentLength((int)file.length());

           // Open the file and output streams
           FileInputStream in;
                   try {
                           in = new FileInputStream(file);
                           OutputStream out = response.getOutputStream();
                           byte[] buf = new byte[1024];
                           int count = 0;
                           while ((count = in.read(buf)) >= 0) {
                                   out.write(buf, 0, count);
                           }
                           in.close();
                           out.close();
                   } catch (Exception e) {
                	   	e.printStackTrace();
                   }
			
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
